/*
 * @Author: liyin 2179253556@qq.com
 * @Date: 2023-04-28 16:42:59
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2025-05-26 16:55:24
 * @FilePath: util.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { ElLoading, transferProps } from 'element-plus'
import { AnyKindOfDictionary } from 'lodash'
export default {
  getYear() {
    const dt = new Date()
    const now = dt.getFullYear()
    return ('2009' + '-' + now)
  },
  // 获取当前可视高度
  getClientHeight() {
    const clientHeight = window.innerHeight
    return clientHeight
  },
  formatFileSize(size: any) {
    if (size < 1024) {
      return size + ' B';
    } else if (size < 1024 * 1024) {
      return (size / 1024).toFixed(2) + ' KB';
    } else if (size < 1024 * 1024 * 1024) {
      return (size / (1024 * 1024)).toFixed(2) + ' MB';
    } else {
      return (size / (1024 * 1024 * 1024)).toFixed(2) + ' GB';
    }
  },
  // 搜索框防抖函数
  debounce(cb: any, delay: any) {
    let timer: any = null
    return function (this: unknown, ...args: any) {
      if (timer) {
        clearTimeout(timer)
      }
      timer = setTimeout(() => {
        cb.call(this, ...args)
      }, delay)
    }
  },
  /* 全局加载层设置 */
  baseLoading(index: any, text: any) {
    let loading
    if (!index) {
      console.log('进来了1')
      loading = ElLoading.service({
        lock: true,
        text: text,
        background: 'hsla(0,0%,100%,.8)',
      })
    } else {
      console.log('进来了2')
      loading = ElLoading.service({
        lock: true,
        text: text,
        spinner: 'vab-loading-type' + index,
        background: 'hsla(0,0%,100%,.8)',
      })
    }
    return loading
  },
  // 回显数据字典
  selectDictLabel(datas: any, value: any) {
    if (value === undefined) {
      return "";
    }
    var actions = [];
    Object.keys(datas).some((key) => {
      if (datas[key].dictValue == ('' + value)) {
        actions.push(datas[key].dictLabel);
        return true;
      }
    })
    if (actions.length === 0) {
      actions.push(value);
    }
    return actions.join('');
  },
  // 添加日期范围
  addDateRange(params: any, dateRange: any,) {
    let search = params;
    search.params = typeof (search.params) === 'object' && search.params !== null && !Array.isArray(search.params) ? search.params : {};
    dateRange = Array.isArray(dateRange) ? dateRange : [];
    search.params['beginTime'] = dateRange[0];
    search.params['endTime'] = dateRange[1];
    return search;
  },
  tansParams(params: any) {
    let result = ''
    for (const propName of Object.keys(params)) {
      const value = params[propName];
      var part = encodeURIComponent(propName) + "=";
      if (value !== null && value !== "" && typeof (value) !== "undefined") {
        if (typeof value === 'object') {
          for (const key of Object.keys(value)) {
            if (value[key] !== null && value[key] !== "" && typeof (value[key]) !== 'undefined') {
              let params = propName + '[' + key + ']';
              var subPart = encodeURIComponent(params) + "=";
              result += subPart + encodeURIComponent(value[key]) + "&";
            }
          }
        } else {
          result += part + encodeURIComponent(value) + "&";
        }
      }
    }
    return result
  },
  // 秒数转换成对应的时分秒
  getHMS(time: any) {
    let ms = time * 1000; // 转成毫秒
    let date = new Date(ms);
    let hour = date.getUTCHours();
    let minute = date.getMinutes();
    let second = date.getSeconds();
    let formatTime = `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}:${second.toString().padStart(2, '0')}`;
    return formatTime
  },
  // 获取当前时间
  getInvalidTime() {
    let dt = new Date()
    const y = dt.getFullYear()
    const m = (dt.getMonth() + 1 + '').padStart(2, '0')
    const d = (dt.getDate() + '').padStart(2, '0')

    const hh = (dt.getHours() + '').padStart(2, '0')
    const mm = (dt.getMinutes() + '').padStart(2, '0')
    const ss = (dt.getSeconds() + '').padStart(2, '0')
    let now = `${y}年${m}月${d}日 ${hh}:${mm}:${ss}`
    return now
  },
  checkNumber(value: any, minLimit: any, maxLimit: any) {
    // 检查必须为整数
    value = Math.floor(value);
    if (value < minLimit) {
      value = minLimit;
    } else if (value > maxLimit) {
      value = maxLimit;
    }
    return value;
  },
  // 查找所有父节点
  getAllParentArr(list: any, id: string | number) {
    for (const i in list) {
      if (list[i].id === id) {
        // 查询到返回该数组对象
        // console.log(list[i])
        return [list[i]]
      }
      if (list[i].child) {
        const node: any = this.getAllParentArr(list[i].child, id)
        if (node !== undefined) {
          // 查询到把父节点连起来
          return node.concat(list[i])
        }
      }
    }
  },
  // 递归去除没有id的数据
  removeNodesWithoutId(node: any) {
    if (!node.child) {
      return; // 没有子节点，直接返回
    }
    node.child = node.child.filter((item: any) => {
      if (item.id) { // 如果当前节点有id，保留它并递归检查其子节点
        this.removeNodesWithoutId(item)// 递归调用以检查子节点
        return true; // 返回true以保留这个节点
      } else { // 如果当前节点没有id，则不保留它
        return false; // 但我们不直接返回false，因为我们需要过滤掉它，并递归检查其子节点以防万一（尽管在这种情况下通常不需要）
      }
    })
  },
  random_string(len?: any){
      len = len || 32
      var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
      var maxPos = chars.length
      var pwd = ''
      for (let i = 0; i < len; i++) {
          pwd += chars.charAt(Math.floor(Math.random() * maxPos))
      }
      return pwd
  },
  // 获取文件信息
  getSuffix(fileName: any){
      var pos = fileName.lastIndexOf('.')
      var suffix = ''
      if (pos !== -1) {
          suffix = fileName.substring(pos)
      }
      return suffix
  }
}